#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
# author: 小菠萝测试笔记
# blog:  https://www.cnblogs.com/poloyy/
# time: 2021/10/14 4:28 下午
# file: users.py
"""

from typing import Dict, Tuple, Union

from fastapi import APIRouter, Body, Depends, HTTPException, Path, status
from fastapi.encoders import jsonable_encoder
from sqlalchemy.orm import Session

from app.api.deps import get_current_active_user, get_db
from app.core.myenum import States
from app.schemas import UserPage
from app.schemas.responses import SelfResponse, StateResponse, UserResponse
from app.schemas.user import *
from app.utils.request_utils import delete_data, get_list_data
from app.config.setting import settings
from app import crud

router = APIRouter(
    dependencies=[
        # Depends(get_current_active_user)
    ]
)


@router.post("/create", response_model=UserResponse)
async def create_user(user_create: UserCreate, db: Session = Depends(get_db)) -> Dict:
    """
    ### 注册功能
    - :param user: UserCreate Model，重点看 JSON schema
    - :param db: 数据库对象
    - :return: UserResponse Model
    """
    if crud.user.get_by_username(db, username=user_create.username):
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="用户名已存在")

    if crud.user.get_by_email(db, email=user_create.email):
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="邮箱已存在")

    if crud.user.get_by_phone(db, phone=user_create.phone):
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="手机已存在")

    user = crud.user.create(db, user_create=user_create)
    return {"code": 200, "msg": "注册成功", "id": user.id, "user": jsonable_encoder(user)}


@router.post("/user_list", response_model=UserList)
async def get_user_list(
    user_page: UserPage, db: Session = Depends(get_db)
) -> Union[Dict, Tuple]:
    """
    ### 批量获取用户
    - :param user_page: UserPage Model（前端不用传）
    - :param db: 数据库对象
    - :return: User Model
    """
    res = get_list_data(user_page, db, crud.user, "users")
    return res


@router.delete("/delete/{id}", response_model=SelfResponse)
async def delete_user(
    id: int = Path(..., description="用户ID"), db: Session = Depends(get_db)
) -> Dict:
    """
    ### 删除用户
    - :param id: 用户id，是主键 id
    - :param db: 数据库对象
    - :return: 自定义 Response
    """
    res = delete_data(id, db, crud.user, "user")
    return res


@router.put("/update", response_model=SelfResponse)
async def update_user(user_update: UserUpdate, db: Session = Depends(get_db)) -> Dict:
    """
    ### 更新用户
    - :param user_update: UserUpdate Model，重点看 JSON schema
    - :param db: 数据库对象
    - :return: 自定义 Response
    """
    user_db = crud.user.get(db, id=user_update.id)

    if not user_db:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")

    user_check = crud.user.get_by_username(db, username=user_update.username)
    if user_check and user_check.id != user_db.id:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="用户名已存在")

    user_check = crud.user.get_by_email(db, email=user_update.email)
    if user_check and user_check.id != user_db.id:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="邮箱已存在")

    user_check = crud.user.get_by_phone(db, phone=user_update.phone)
    if user_check and user_check.id != user_db.id:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="手机已存在")

    user = crud.user.update(db, db_obj=user_db, obj_in=user_update)
    return {"code": 200, "msg": "更新成功", "id": user.id}


@router.put("/active/{id}", response_model=StateResponse)
async def active_user(
    id: int = Path(..., description="用户ID"),
    state: States = Body(default=States.ACTIVE, description="用户状态", embed=True),
    db: Session = Depends(get_db),
) -> Dict:
    """
    ### 更新用户状态
    -  :param id: 用户id，是主键 id
    - :param state: 用户状态m，只能是 0 或 1
    - :param db: 数据库对象
    :return: 自定义 Response
    """
    user = crud.user.active_user(db, id=id, state=state)
    if not user:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
    return {"code": 200, "msg": "修改状态成功", "id": id, "state": state}
